/*********************************************************
 * copyright learnren.com 版权所有 
 * 开发人员：ivan.yu
 * 创建时间：2013/5/3 17:13:17
 * 描述说明：
 * 
 * 更改历史：
 * 
 * *******************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Configuration.Common;
using System.Web.Security;
using LEARNREN.COM.Entity;
using LEARNREN.COM.TOOL;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Configuration;
using System.Web.Configuration;
using System.Security.Cryptography;

namespace LEARNREN.COM.BLL
{
    /// <summary>
    /// 自定义MemberShip
    /// </summary>
    public class TopMembershipProvider : System.Web.Security.MembershipProvider
    {
        #region 字段

        private int newPasswordLength = 8;
        private string connectionString;
        private bool _WriteExceptionsToEventLog;
        private MachineKeySection machineKey;

        #endregion 字段

        #region 属性

        private string _ApplicationName;
        private bool _EnablePasswordReset;
        private bool _EnablePasswordRetrieval;
        private int _MaxInvalidPasswordAttempts;
        private int _MinRequiredPasswordLength;
        private int _MinRequiredNonAlphanumericCharacters;
        private int _PasswordAttemptWindow;
        private MembershipPasswordFormat _PasswordFormat;
        private string _PasswordStrengthRegularExpression;
        private bool _RequiresQuestionAndAnswer;
        private bool _RequiresUniqueEmail;

        public override string ApplicationName
        {
            get
            {
                return _ApplicationName;
            }
            set
            {
                _ApplicationName = value;
            }
        }

        public override bool EnablePasswordReset
        {
            get { return _EnablePasswordReset; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return _EnablePasswordRetrieval; }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return _MaxInvalidPasswordAttempts; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return _MinRequiredNonAlphanumericCharacters; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return _MinRequiredPasswordLength; }
        }

        public override int PasswordAttemptWindow
        {
            get { return _PasswordAttemptWindow; }
        }

        public override System.Web.Security.MembershipPasswordFormat PasswordFormat
        {
            get { return _PasswordFormat; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return _PasswordStrengthRegularExpression; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get
            {
                return _RequiresQuestionAndAnswer;
            }
        }

        public override bool RequiresUniqueEmail
        {
            get { return _RequiresUniqueEmail; }
        }

        #endregion 属性

        #region 重写方法

        public override void Initialize(string name, NameValueCollection config)
        {
            //
            // Initialize values from web.config.
            //

            if (config == null)
                throw new ArgumentNullException("config");

            if (name == null || name.Length == 0)
                name = "Db4oMembershipProvider";

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Sample Db4o Membership provider");
            }

            // Initialize the abstract base class.
            base.Initialize(name, config);

            _ApplicationName = GetConfigValue(config["applicationName"],
                                            System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
            _MaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
            _PasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10"));
            _MinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1"));
            _MinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7"));
            _PasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], ""));
            _EnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true"));
            _EnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true"));
            _RequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false"));
            _RequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true"));
            _WriteExceptionsToEventLog = Convert.ToBoolean(GetConfigValue(config["writeExceptionsToEventLog"], "true"));

            string temp_format = config["passwordFormat"];
            if (temp_format == null)
            {
                temp_format = "Hashed";
            }

            switch (temp_format)
            {
                case "Hashed":
                    _PasswordFormat = MembershipPasswordFormat.Hashed;
                    break;
                case "Encrypted":
                    _PasswordFormat = MembershipPasswordFormat.Encrypted;
                    break;
                case "Clear":
                    _PasswordFormat = MembershipPasswordFormat.Clear;
                    break;
                default:
                    throw new ProviderException("Password format not supported.");
            }

            // Initialize Connection
            ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
            if (ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim() == "")
            {
                throw new ProviderException("Connection string cannot be blank.");
            }

            connectionString = ConnectionStringSettings.ConnectionString;

            // Get encryption and decryption key information from the configuration.
            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
            machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey");

            if (machineKey.ValidationKey.Contains("AutoGenerate"))
                if (PasswordFormat != MembershipPasswordFormat.Clear)
                    throw new ProviderException("Hashed or Encrypted passwords " +
                                                "are not supported with auto-generated keys.");
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="username"></param>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser user;
                    if (CheckUser(username, oldPassword, logic, out user))
                    {
                        ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true);
                        OnValidatingPassword(args);
                        if (args.Cancel)
                            if (args.FailureInformation != null)
                                throw args.FailureInformation;
                            else
                                throw new MembershipPasswordException("Change password canceled due to new password validation failure.");

                        user.Password = EncodePassword(newPassword);
                        user.SetLastPasswordChangedDate(DateTime.Now);

                        logic.Save(user);
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                return false;
            }
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser user;
                    if (CheckUser(username, password, logic, out user))
                    {
                        user.SetPasswordQuestion(newPasswordQuestion);
                        user.PasswordAnswer = EncodePassword(newPasswordAnswer);
                        logic.Save(user);
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                return false;
            }
        }

        public override System.Web.Security.MembershipUser CreateUser(string username,
                                                                        string password,
                                                                        string email,
                                                                        string passwordQuestion,
                                                                        string passwordAnswer,
                                                                        bool isApproved,
                                                                        object providerUserKey,
                                                                        out System.Web.Security.MembershipCreateStatus status)
        {
            try
            {
                if (password.Length < _MinRequiredPasswordLength)
                {
                    status = MembershipCreateStatus.InvalidPassword;
                    return null;
                }

                ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);

                OnValidatingPassword(args);

                if (args.Cancel)
                {
                    status = MembershipCreateStatus.InvalidPassword;
                    return null;
                }

                if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
                {
                    status = MembershipCreateStatus.DuplicateEmail;
                    return null;
                }
                MembershipUser u = GetUser(username, false);
                if (u == null)
                {
                    DateTime createTime = DateTime.Now;
                    if (providerUserKey == null)
                    {
                        providerUserKey = Guid.NewGuid();
                    }
                    else
                    {
                        if (!(providerUserKey is Guid))
                        {
                            status = MembershipCreateStatus.InvalidProviderUserKey;
                            return null;
                        }
                    }

                    TopUser user = new TopUser(this.Name,
                                        username,
                                        providerUserKey,
                                        email,
                                        passwordQuestion,
                                        "",
                                        isApproved,
                                        false,
                                        createTime,
                                        DateTime.MinValue,
                                        DateTime.MinValue,
                                        createTime,
                                        DateTime.MinValue,
                                        _ApplicationName);

                    user.Password = EncodePassword(password);
                    user.PasswordAnswer = EncodePassword(passwordAnswer);
                    user.FailedPasswordAnswerAttemptCount = 0;
                    user.FailedPasswordAnswerAttemptWindowStart = DateTime.MinValue;
                    user.FailedPasswordAttemptCount = 0;
                    user.FailedPasswordAttemptWindowStart = DateTime.MinValue;

                    using (MembershipUserLogic logic = new MembershipUserLogic())
                    {
                        logic.Save(user);
                        status = System.Web.Security.MembershipCreateStatus.Success;
                        return user;
                    }
                }
                else
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                    return null;
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                status = System.Web.Security.MembershipCreateStatus.ProviderError;
                return null;
            }
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser user = logic.GetList(p => p.UserName == username).FirstOrDefault();

                    if (user != null)
                    {
                        logic.Delete(user);
                    }

                    if (deleteAllRelatedData)
                    {
                        // 删除相关数据

                    }

                    return true;
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                return false;
            }
        }

        public override System.Web.Security.MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection users = new MembershipUserCollection();
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    List<TopUser> usersInDB = logic.GetListByPage(out totalRecords,
                                                                p => p.Email.Contains(emailToMatch) && p.ApplicationName == _ApplicationName,
                                                                p => p.UserName,
                                                                Enums.OrderEnum.Ascending,
                                                                pageSize, pageIndex);
                    foreach (var user in usersInDB)
                    {
                        users.Add(user);
                    }
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                totalRecords = 0;
            }
            return users;
        }

        public override System.Web.Security.MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection users = new MembershipUserCollection();
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    List<TopUser> usersInDB = logic.GetListByPage(out totalRecords,
                                                                p => p.UserName.Contains(usernameToMatch) && p.ApplicationName == _ApplicationName,
                                                                p => p.UserName,
                                                                Enums.OrderEnum.Ascending,
                                                                pageSize, pageIndex);
                    foreach (var user in usersInDB)
                    {
                        users.Add(user);
                    }
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                totalRecords = 0;
            }
            return users;
        }

        public override System.Web.Security.MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection users = new MembershipUserCollection();
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    List<TopUser> usersInDB = logic.GetListByPage(out totalRecords,
                                                                p => p.ApplicationName == _ApplicationName,
                                                                p => p.UserName,
                                                                Enums.OrderEnum.Ascending,
                                                                pageSize, pageIndex);
                    foreach (var user in usersInDB)
                    {
                        users.Add(user);
                    }
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                totalRecords = 0;
            }
            return users;
        }

        public override int GetNumberOfUsersOnline()
        {
            try
            {
                TimeSpan onlineSpan = new TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0);
                DateTime compareTime = DateTime.Now.Subtract(onlineSpan);
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    return logic.GetList(p => p.ApplicationName == _ApplicationName && p.LastActivityDate > compareTime).Count;
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                return 0;
            }
        }

        public override string GetPassword(string username, string answer)
        {
            if (!EnablePasswordRetrieval)
            {
                throw new ProviderException("Password Retrieval Not Enabled.");
            }

            if (PasswordFormat == MembershipPasswordFormat.Hashed)
            {
                throw new ProviderException("Cannot retrieve Hashed passwords.");
            }

            string password = "";
            string passwordAnswer = "";

            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser user = logic.GetList(p => p.UserName == username && p.ApplicationName == _ApplicationName).FirstOrDefault();
                    if (user != null)
                    {
                        if (user.IsLockedOut)
                        {
                            throw new MembershipPasswordException("指定的用户已经被锁定。");
                        }

                        password = user.Password;
                        passwordAnswer = user.PasswordAnswer;

                        if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer))
                        {
                            UpdateFailureCount(user, "passwordAnswer", logic);

                            throw new MembershipPasswordException("密码问题答案错误。");
                        }
                    }
                    else
                    {
                        throw new MembershipPasswordException("未找到指定的用户名。");
                    }
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
            }

            if (PasswordFormat == MembershipPasswordFormat.Encrypted)
            {
                password = UnEncodePassword(password);
            }

            return password;
        }

        public override System.Web.Security.MembershipUser GetUser(string username, bool userIsOnline)
        {
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser user = logic.GetList(p => p.UserName == username && p.ApplicationName == _ApplicationName).FirstOrDefault();
                    if (user == null)
                    {
                        return null;
                    }

                    if (userIsOnline)
                    {
                        user.LastActivityDate = DateTime.Now;
                        logic.Save(user);
                    }
                    return user;
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                return null;
            }
        }

        public override System.Web.Security.MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser user = logic.GetList(p => p.ProviderUserKey == providerUserKey && p.ApplicationName == _ApplicationName).FirstOrDefault();
                    if (user == null)
                    {
                        return null;
                    }

                    if (userIsOnline)
                    {
                        user.LastActivityDate = DateTime.Now;
                        logic.Save(user);
                    }
                    return user;
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                return null;
            }
        }

        public override string GetUserNameByEmail(string email)
        {
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser user = logic.GetList(p => p.Email == email && p.ApplicationName == _ApplicationName).FirstOrDefault();
                    if (user == null)
                    {
                        return "";
                    }
                    return user.UserName;
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                return "";
            }
        }

        public override string ResetPassword(string username, string answer)
        {
            if (!EnablePasswordReset)
            {
                throw new NotSupportedException("Password reset is not enabled.");
            }

            string newPassword = System.Web.Security.Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters);


            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true);

            OnValidatingPassword(args);

            if (args.Cancel)
            {
                if (args.FailureInformation != null)
                { throw args.FailureInformation; }
                else
                { throw new MembershipPasswordException("Reset password canceled due to password validation failure."); }
            }


            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser user = logic.GetList(p => p.UserName == username && p.ApplicationName == _ApplicationName).FirstOrDefault();
                    if (user == null)
                    {
                        throw new MembershipPasswordException("The supplied user name is not found.");
                    }
                    else if (user.IsLockedOut)
                    {
                        throw new MembershipPasswordException("The supplied user is locked out.");
                    }
                    else
                    {
                        if (answer == null && RequiresQuestionAndAnswer)
                        {
                            UpdateFailureCount(user, "passwordAnswer", logic);

                            throw new ProviderException("重置密码需要输入密码提示问题答案。");
                        }

                        if (RequiresQuestionAndAnswer && !CheckPassword(answer, user.PasswordAnswer))
                        {
                            UpdateFailureCount(user, "passwordAnswer", logic);

                            throw new MembershipPasswordException("Incorrect password answer.");
                        }

                        user.Password = EncodePassword(newPassword);
                        user.SetLastPasswordChangedDate(DateTime.Now);
                        logic.Save(user);
                        return user.Password;
                    }
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                throw new MembershipPasswordException(ex.Message);
            }
        }

        public override bool UnlockUser(string userName)
        {
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser user = logic.GetList(p => p.UserName == userName && p.ApplicationName == _ApplicationName).FirstOrDefault();
                    if (user != null)
                    {
                        user.SetIsLockedOut(false);
                        logic.Save(user);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                return false;
            }
        }

        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser userInDB = GetUserByName(user.UserName, logic);

                    if (userInDB != null)
                    {
                        userInDB.Email = user.Email;
                        userInDB.Comment = user.Comment;
                        userInDB.IsApproved = user.IsApproved;

                        logic.Save(userInDB);
                    }
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
            }
        }

        public override bool ValidateUser(string username, string password)
        {
            try
            {
                using (MembershipUserLogic logic = new MembershipUserLogic())
                {
                    TopUser user = null;
                    return CheckUser(username, password, logic, out user);
                }
            }
            catch (Exception ex)
            {
                Loger.LogErr(ex);
                return false;
            }
        }

        #endregion 重写方法

        #region 私有方法

        private bool CheckUser(string username, string password, MembershipUserLogic logic, out TopUser topuser)
        {
            TopUser user = logic.GetList(p => p.UserName == username && p.ApplicationName == _ApplicationName && !p.IsLockedOut).FirstOrDefault();
            topuser = user;
            if (user != null)
            {
                if (CheckPassword(password, user.Password))
                {
                    if (user.IsApproved)
                    {
                        user.LastLoginDate = DateTime.Now;
                        logic.Save(user);
                        return true;
                    }
                    return false;
                }
                else
                {
                    UpdateFailureCount(user, "password", logic);
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        private void UpdateFailureCount(TopUser user, string failureType, MembershipUserLogic logic)
        {
            DateTime windowStart = new DateTime();
            int failureCount = 0;

            try
            {
                if (user != null)
                {
                    if (failureType == "password")
                    {
                        failureCount = user.FailedPasswordAttemptCount;
                        windowStart = user.FailedPasswordAttemptWindowStart;
                    }

                    if (failureType == "passwordAnswer")
                    {
                        failureCount = user.FailedPasswordAnswerAttemptCount;
                        windowStart = user.FailedPasswordAnswerAttemptWindowStart;
                    }
                }

                DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow);

                if (failureCount == 0 || DateTime.Now > windowEnd)
                {
                    // First password failure or outside of PasswordAttemptWindow. 
                    // Start a new password failure count from 1 and a new window starting now.

                    if (failureType == "password")
                    {
                        user.FailedPasswordAttemptCount = 1;
                        user.FailedPasswordAttemptWindowStart = DateTime.Now;
                    }

                    if (failureType == "passwordAnswer")
                    {
                        user.FailedPasswordAnswerAttemptCount = 1;
                        user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now;
                    }
                    logic.Save(user);
                }
                else
                {
                    if (failureCount++ >= MaxInvalidPasswordAttempts)
                    {
                        // Password attempts have exceeded the failure threshold. Lock out
                        // the user.

                        user.SetIsLockedOut(true);
                        user.SetLastLockoutDate(DateTime.Now);
                        logic.Save(user);
                    }
                    else
                    {
                        // Password attempts have not exceeded the failure threshold. Update
                        // the failure counts. Leave the window the same.

                        if (failureType == "password")
                        {
                            user.FailedPasswordAttemptCount = failureCount;
                        }

                        if (failureType == "passwordAnswer")
                        {
                            user.FailedPasswordAnswerAttemptCount = failureCount;
                        }
                        logic.Save(user);
                    }
                }
            }
            catch (Exception e)
            {
                Loger.LogErr(e);
            }
        }

        //
        // A helper function to retrieve config values from the configuration file.
        //
        private string GetConfigValue(string configValue, string defaultValue)
        {
            if (String.IsNullOrEmpty(configValue))
                return defaultValue;

            return configValue;
        }

        private bool CheckPassword(string password, string dbpassword)
        {
            string pass1 = password;
            string pass2 = dbpassword;

            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Encrypted:
                    pass2 = UnEncodePassword(dbpassword);
                    break;
                case MembershipPasswordFormat.Hashed:
                    pass1 = EncodePassword(password);
                    break;
                default:
                    break;
            }

            if (pass1 == pass2)
            {
                return true;
            }

            return false;
        }

        private string EncodePassword(string password)
        {
            string encodedPassword = password;

            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Clear:
                    break;
                case MembershipPasswordFormat.Encrypted:
                    encodedPassword =
                      Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
                    break;
                case MembershipPasswordFormat.Hashed:
                    HMACSHA1 hash = new HMACSHA1();
                    hash.Key = HexToByte(machineKey.ValidationKey);
                    encodedPassword =
                      Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
                    break;
                default:
                    throw new ProviderException("Unsupported password format.");
            }

            return encodedPassword;
        }

        private string UnEncodePassword(string encodedPassword)
        {
            string password = encodedPassword;

            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Clear:
                    break;
                case MembershipPasswordFormat.Encrypted:
                    password =
                      Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
                    break;
                case MembershipPasswordFormat.Hashed:
                    throw new ProviderException("Cannot unencode a hashed password.");
                default:
                    throw new ProviderException("Unsupported password format.");
            }

            return password;
        }

        private byte[] HexToByte(string hexString)
        {
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        private TopUser GetUserByName(string userName, MembershipUserLogic logic)
        {
            return logic.GetList(p => p.UserName == userName && p.ApplicationName == _ApplicationName).FirstOrDefault();
        }

        #endregion 私有方法
    }
}
